package chris.config;

import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.QueueBuilder;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.boot.autoconfigure.amqp.RabbitProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.retry.backoff.ExponentialBackOffPolicy;
import org.springframework.retry.support.RetryTemplate;

import javax.annotation.Resource;

/**
 * RabbitmqConfig
 *
 * @author nanxin.chen
 * @since 2017/6/30
 */
@Configuration
@EnableConfigurationProperties({RabbitProperties.class})
public class RabbitmqConfig {

    public static final String HELLO_WORLD_QUEUE_NAME = "hello_queue";

    @Resource
    private RabbitProperties rabbitProperties;


    @Bean
    public ConnectionFactory connectionFactory() {
        CachingConnectionFactory cf = new CachingConnectionFactory();
        cf.setHost(rabbitProperties.getHost());
        cf.setPort(rabbitProperties.getPort());
//        cf.setAddresses(rabbitProperties.getAddresses());  //for clustered environment
        cf.setUsername(rabbitProperties.getUsername());
        cf.setPassword(rabbitProperties.getPassword());
        cf.setVirtualHost("/");
        cf.setPublisherConfirms(true);
        cf.setPublisherReturns(true);
        cf.setConnectionNameStrategy(connectionFactory -> "chris-mq-cn-");
        return cf;
    }


    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        return new RabbitTemplate(connectionFactory);
    }


    /**
     * 利用 spring-retry https://github.com/spring-projects/spring-retry
     * 实现rabbitTemplate的retry调用
     *
     * @param connectionFactory
     * @return
     */
    @Bean
    public RabbitTemplate retryRabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate template = new RabbitTemplate(connectionFactory);

        RetryTemplate retryTemplate = new RetryTemplate();
        ExponentialBackOffPolicy backOffPolicy = new ExponentialBackOffPolicy();
        backOffPolicy.setInitialInterval(500);
        backOffPolicy.setMultiplier(10.0);
        backOffPolicy.setMaxInterval(10000);
        retryTemplate.setBackOffPolicy(backOffPolicy);

        template.setRetryTemplate(retryTemplate);
        return template;
    }


    @Bean
    public Queue helloWorldQueue() {
        return QueueBuilder.durable(HELLO_WORLD_QUEUE_NAME)
                .build();
    }






}
